package com.generic.mybatis.dal.dao.type;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;

/**
 * 将string转为List
 */
@MappedTypes(value = Map.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MapStringTypeHandler extends BaseTypeHandler<Map<String, String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, String> parameter, JdbcType jdbcType)
            throws SQLException {
        String val = null;
        if (parameter != null) {
            Joiner.MapJoiner joiner = Joiner.on(",").skipNulls().withKeyValueSeparator(":");
            val = joiner.join(parameter);
        }

        ps.setString(i, val);
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String val = rs.getString(columnName);
        if (val != null) {
            Splitter.MapSplitter splitter = Splitter.on(",").withKeyValueSeparator(":");
            return splitter.split(val);
        } else {
            return Collections.emptyMap();
        }
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        String val = rs.getString(columnIndex);
        if (val != null) {
            Splitter.MapSplitter splitter = Splitter.on(",").withKeyValueSeparator(":");
            return splitter.split(val);
        } else {
            return Collections.emptyMap();
        }
    }

    @Override
    public Map<String, String> getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String val = cs.getString(columnIndex);
        if (val != null) {
            Splitter.MapSplitter splitter = Splitter.on(",").withKeyValueSeparator(":");
            return splitter.split(val);
        } else {
            return Collections.emptyMap();
        }
    }
}